<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="业务标题">
              <j-input placeholder="请输入业务标题" v-model="queryParam.bizBpmTitle"></j-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="流程名称">
              <j-input placeholder="请输入流程名称" v-model="queryParam.draftType"></j-input>
            </a-form-item>
          </a-col>
          <!--
          <a-col :md="6" :sm="12">
            <a-form-item label="流程编号">
              <a-input placeholder="请输入流程编号" v-model="queryParam.processDefinitionId"></a-input>
            </a-form-item>
          </a-col> -->
          <a-col :md="8" :sm="12">
            <a-form-item label="办理时间" >
              <a-range-picker
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
                v-model="createTimeRange"
                @change="(dates, dateStrs) => { queryParam.createTime_begin = dateStrs[0]; queryParam.createTime_end = dateStrs[1] }"
                style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        :scroll="{x: scrollX}"
        :components="draggableComponent"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        <span slot="bizBpmTitle" slot-scope="text, record" :title="record.processFlag&&(record.processFlag == 4 || record.processFlag == 'reject')?'【退回】'+text:text">
          <span style="color: #dd1a32;font-weight:600" v-show="record.processFlag&&(record.processFlag == 4 || record.processFlag == 'reject')">【退回】</span>{{ record.bizBpmTitle }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="edit"
              @click="handleEdit(record)"
            />
            <template v-if="record.isAllowDel=='1'">
            <a-divider type="vertical"/>
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
              <a-button
                class="ruleButton"
                :ghost="true"
                type="primary"
                icon="delete"/>
            </a-popconfirm>
            </template>
          </template>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 弹出框 -->
    <his-task-deal-modal ref="taskDealModal" :path="path" :formData="formData"></his-task-deal-modal>
    <task-notify-modal ref="taskNotifyModal"></task-notify-modal>
    <select-forward-modal ref="selectForwardModal" @selectFinished="handleForward"></select-forward-modal>
    <select-single-user-modal ref="selectSingleUserModal" @selectFinished="selectUserOK"></select-single-user-modal>
    <MyCommittedModules
      ref="modalForm"
      @ok="modalFormOk"
      :recordDetail="recordDetail"
      :formUrl="formUrl"
    ></MyCommittedModules>
    <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
  </a-card>
</template>

<script>
import { putAction, deleteAction, getAction } from '@/api/manage'
import HisTaskDealModal from './HisTaskDealModal';
import JEllipsis from '@/components/jeecg/JEllipsis'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { BpmNodeInfoMixin } from '@/views/modules/bpm/mixins/BpmNodeInfoMixin'
import TaskNotifyModal from '../../extbpm/process/TaskNotifyModal';
import SelectForwardModal from '@/views/modules/bpm/task/form/SelectForwardModal';
import SelectSingleUserModal from '@/views/modules/bpm/task/form/SelectSingleUserModal.vue';
import MyCommittedModules from './modules/MyCommittedModules'; // 公共弹窗
import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal' // 流程弹窗
export default {
    name: 'MyApplyProcessList',
    mixins: [JeecgListMixin, BpmNodeInfoMixin],
    components: {
      TaskNotifyModal,
      HisTaskDealModal,
      SelectSingleUserModal,
      SelectForwardModal,
      JEllipsis,
      MyCommittedModules,
      ProcessConfigModal
    },
    data() {
      return {
        /* 排序参数 */
        isorter: {
          column: '',
          order: ''
        },
        recordDetail: {},
        formUrl: '',
        createTimeRange: [],
        description: '我发起的流程',
        queryParam: {},
        dataSource: [],
        loading: false,
        columns: [
          {
            title: '序号',
            dataIndex: '',
            width: 60,
            key: 'rowIndex',
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '业务标题',
            align: 'center',
            dataIndex: 'bizBpmTitle',
            width: 120,
            ellipsis: true,
            scopedSlots: { customRender: 'bizBpmTitle' }
          },
          {
            title: '流程名称',
            align: 'center',
            dataIndex: 'draftType',
            width: 100,
            ellipsis: true
            // scopedSlots: { customRender: 'draftType' }
          },
          {
            title: '发起人',
            align: 'center',
            width: 120,
            ellipsis: true,
            dataIndex: 'userName_dictText'
          },
          {
            title: '发起日期',
            align: 'center',
            width: 100,
            ellipsis: true,
            dataIndex: 'createTime',
            customRender: function (text) {
              return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
          },
          // {
          //   title: '结束时间',
          //   align: 'center',
          //   width: 100,
          //   ellipsis: true,
          //   dataIndex: 'endTime'
          // },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'processFlag',
            // fixed: 'right',
            width: 120,
            customRender: (text) => {
              switch (text) {
                case '1':
                  return '待提交';
                case '2':
                  return '处理中';
                case '3':
                  return '已完成';
                case '4':
                  return '已退回';
                case '5':
                  return '已挂起';
                case 'draft':
                  return '待提交';
                  case 'reject':
                  return '已退回';
                case 'rejectProcess':
                  return '已驳回';
                case 'callBackProcess':
                  return '已取回';
                case 'invalidProcess':
                  return '已作废';
              }
              return text;
            }
          },
          {
            title: '操作',
            align: 'center',
            // fixed: 'right',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            width: 120
          }

        ],
        url: {
          list: '/api/erp/deformDraft/erpActDeformDraftRecord/queryClientList',
          invalidProcess: '/api/erpmng/act/task/invalidProcess',
          callBackProcess: '/api/erpmng/act/task/callBackProcess',
          taskForward: '/api/erpmng/act/task/taskForward'
        },
        path: 'modules/bpm/task/form/FormLoading',
        formData: {},
        taskId: '',
        bizBpmTitle: '',
        processInstanceId: ''

      }
    },
    methods: {
      // 点击编辑
      handleEdit (record) {
        getAction(record.detailApi, { id: record.dataId }).then((res) => {
          if (res.success) {
            this.recordDetail = record
            this.formUrl = record && record.pcFormUrl ? record.pcFormUrl : ''
            if (this.formUrl && this.formUrl == '/oa/erpcarusing/modules/ErpCarUsingForm') {
              this.$refs.modalForm.isStaging = false
            } else {
              this.$refs.modalForm.isStaging = true
            }
            let data = res.result
            if(data.records){
              data = res.result.records[0]
            }
            this.$refs.modalForm.edit(data);
            this.$refs.modalForm.title = '编辑';
            this.$refs.modalForm.disableSubmit = false;
          } else {
            this.$message.warning('查询失败，请重新刷新页面！')
          }
        })
      },

      beginProcess(record) {
        // 当是项目收款合同和项目收款合同变更时
        if (this.recordDetail && this.recordDetail.appUrl && (this.recordDetail.appUrl == '/pages/contract/ErpOmcCollectContractManagerForm' || this.recordDetail.appUrl == '/pages/contract/ErpOmcCollectContractManagerChangeForm')) {
          getAction('/api/erp/omc/contractmanager/erpOmcContractManager/checkContractById', { id: record.id }).then((res) => {
            if (res.success) {
              this.$refs.processConfig.visible = true
              this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
              this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
              this.$refs.processConfig.flowCode = this.recordDetail.flowCode
              this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
            } else {
              this.$message.warning(res.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是平台账号申请变更时
        if (this.recordDetail && this.recordDetail.appUrl && this.recordDetail.appUrl == '/pages/project/ErpOmcPlatformAccountChangeForm') {
          getAction('/api/erp/omc/platformaccount/erpOmcPlatformAccountFinal/updateStatus', { code: record.ptzhbm }).then((res) => {
            if (res.code == 200) {
            this.$refs.processConfig.visible = true
            this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
            this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
            this.$refs.processConfig.flowCode = this.recordDetail.flowCode
            this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
          } else {
            this.$message.warning(res.message)
            this.handleClose()
          }
          })
          return false
        }
        // 当是立项申请和立项申请变更时
        if (this.recordDetail && this.recordDetail.appUrl && (this.recordDetail.appUrl == '/pages/project/ErpOmcProjectApplyForm' || this.recordDetail.appUrl == '/pages/project/ErpOmcProjectChangeForm')) {
          var projectId = record.finalProjectId ? record.finalProjectId : record.projectId
          getAction('/api/erp/omc/project/erpOmcProject/checkProjectTenderEnd', { id: projectId, type: record.lx, isPrepareEstablish: record.isPrepareEstablish }).then((res) => {
            if (res.success) {
              this.$refs.processConfig.visible = true
              this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
              this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
              this.$refs.processConfig.flowCode = this.recordDetail.flowCode
              this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
            } else {
              this.$message.warning(res.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是报告审核单时
        if (this.recordDetail && this.recordDetail.appUrl && this.recordDetail.appUrl == '/pages/project/ErpReportAuditForm') {
          getAction('/api/erp/omc/project/erpOmcProjectTask/checkTaskChangeById', { id: record.taskId }).then(res => {
            if (res.success) {
              this.$refs.processConfig.visible = true
              this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
              this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
              this.$refs.processConfig.flowCode = this.recordDetail.flowCode
              this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
            } else {
              this.$message.warning(res.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是任务委托和变更任务委托时
        if (this.recordDetail && this.recordDetail.appUrl && (this.recordDetail.appUrl == '/pages/project/ErpOmcTaskDistributionForm' || this.recordDetail.appUrl == '/pages/project/ErpProgressTaskChangeListForm')) {
          getAction('/api/erp/omc/project/erpOmcProjectTask/checkTaskChangeById', { id: record.taskId }).then(res => {
            if (res.success) {
              this.$refs.processConfig.visible = true
              this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
              this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
              this.$refs.processConfig.flowCode = this.recordDetail.flowCode
              this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
            } else {
              this.$message.warning(res.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是任务再委托
        if (this.recordDetail && this.recordDetail.appUrl && this.recordDetail.appUrl == '/pages/project/ErpOmcTaskRedistributionForm') {
          getAction('/api/erp/omc/project/erpOmcProjectTask/checkTaskChangeAndStatusById', { id: record.taskId }).then(res => {
            if (res.success) {
              this.$refs.processConfig.visible = true
              this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
              this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
              this.$refs.processConfig.flowCode = this.recordDetail.flowCode
              this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
            } else {
              this.$message.warning(res.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是投标申请和投标变更时
        if (this.recordDetail && this.recordDetail.pcFormUrl && this.recordDetail.pcFormUrl == '/erp/omc/tender/modules/ErpOmcTenderForm') {
          // 校验结果
          // 校验该预立项是否存在，如果存在则无法提交
          var isJudge1 = getAction('/api/erp/omc/project/erpOmcProject/checkProjectTenderStatus', { id: record.prepareProjectId, type: record.applyType }).then(async(res) => {
            if (res.success) {
              return Promise.resolve(true)
            } else {
              // 校验不通过
              this.$message.warning(res.message)
              this.handleClose()
              return Promise.reject(false)
            }
          })
          // 校验该立项是否有收款合同，若果有则无法提交
          var isJudge2 = getAction('/api/erp/omc/contractmanager/erpOmcContractManagerFinal/totalCount', { xmmc: record.prepareProjectId, htlx: 1 }).then(async(res) => {
            if (res.success) {
              if (res.result > 0) {
                // 校验不通过
                this.$message.warning('该项目已签收款合同，无法进行投标!')
                this.handleClose()
                return Promise.reject(false)
              } else {
                return Promise.resolve(true)
              }
            } else {
              this.$message.warning(res.message)
              this.handleClose()
              return Promise.reject(false)
            }
          })
          Promise.all([isJudge1, isJudge2]).then(() => {
            this.$refs.processConfig.visible = true
            this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
            this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
            this.$refs.processConfig.flowCode = this.recordDetail.flowCode
            this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
          }).catch(() => {
            return false
          })
          return false
        }
        // 当是投标文件审核
        if (this.recordDetail && this.recordDetail.appUrl && this.recordDetail.appUrl == '/pages/project/ErpOmcTenderFileForm') {
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerFinal/totalCount', { tenderFinalCode: record.tenderFinalCode }).then((res) => {
            if (res.success) {
              if (res.result <= 0) {
                this.$refs.processConfig.visible = true
                this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
                this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
                this.$refs.processConfig.flowCode = this.recordDetail.flowCode
                this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
              } else {
                this.$message.warning('该项目已签收款合同，无法进行投标!')
                this.handleClose()
              }
            } else {
              this.$message.warning(res.result.message)
              this.handleClose()
            }
          })
          return false
        }
        // 当是投标结果申请
        if (this.recordDetail && this.recordDetail.appUrl && this.recordDetail.appUrl == '/pages/project/ErpOmcTenderResultForm') {
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerFinal/totalCount', { tenderFinalCode: record.tenderFinalCode }).then((res) => {
            if (res.success) {
              if (res.result <= 0) {
                this.$refs.processConfig.visible = true
                this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
                this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
                this.$refs.processConfig.flowCode = this.recordDetail.flowCode
                this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
              } else {
                this.$message.warning('该项目已签收款合同，无法进行投标!')
                this.handleClose()
              }
            } else {
              this.$message.warning(res.result.message)
              this.handleClose()
            }
          })
          return false
        }
        this.$refs.processConfig.visible = true
        this.$refs.processConfig.formUrl = this.recordDetail.pcFormUrl
        this.$refs.processConfig.formUrlMobile = this.recordDetail.appFormUrl
        this.$refs.processConfig.flowCode = this.recordDetail.flowCode
        this.$refs.processConfig.edit(record, this.recordDetail.processId, this.recordDetail.beanName)
      },
      handleSuccess() {
        this.loadData();
        this.onClearSelected();
        this.$refs.modalForm.handleCancel()
      },

      // 新增流程取消关闭弹窗刷新页面
      handleClose () {
        this.$refs.modalForm.handleCancel()
        this.loadData();
      },

      searchReset() {
        this.createTimeRange = []
        this.queryParam = {}
        this.loadData(1)
      },
      // 流程作废
      invalidProcess(record) {
        var that = this;
        var params = {
          processInstanceId: record.processInstanceId
        };// 查询条件
        putAction(that.url.invalidProcess, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
            that.loadData();
          }
        })
      },
      handleDelete: function (record) {
        if (!record.delApi) {
          this.$message.error('请设置url.delete属性!')
          return
        }
        var that = this
        deleteAction(record.delApi, {
          id: record.dataId
        }).then(res => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData()
            if (that.$refs.search != undefined) {
              that.$refs.search.initDictData();
            }
            if (that.$refs.search2 != undefined) {
              that.$refs.search2.initDictData();
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      // 流程取回
      callBackProcess(record) {
        var that = this;
        var params = {
          processInstanceId: record.processInstanceId
        };// 查询条件
        putAction(that.url.callBackProcess, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
            that.loadData();
          }
        })
      },
      // 历史
      showHistory(record) {
        this.getHisProcessNodeInfo(record);
      },
      // 催办
      taskNotify(record) {
        this.$refs.taskNotifyModal.notify(record);
        this.$refs.taskNotifyModal.title = '催办提醒';
      },
      selectUserOK: function(data) {
        this.model.userName = data.realname;
        this.queryParam.userName = data.username;
      },
      selectForward(record) {
        this.bizBpmTitle = record.bizBpmTitle;
        this.processInstanceId = record.processInstanceId;
        this.$refs.selectForwardModal.select(record);
        this.$refs.selectForwardModal.title = '选择转发人';
      },
      handleForward(data) {
        var that = this;
        var params = {
          taskId: '',
          processInstanceId: this.processInstanceId,
          bpmBizTitle: this.bizBpmTitle,
          taskAssignee: data.username
        };// 查询条件
        putAction(that.url.taskForward, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.handleOk();
          } else {
            that.$message.warning(res.message);
            that.handleOk();
          }
        })
      }
    }

  }
</script>
<style scoped>
  .ant-card-body {
    margin-bottom: 18px;
  }

  .table-operator button {
    margin-bottom: 18px;
    margin-right: 5px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  .anty-img-wrap {
    height: 25px;
    position: relative;
  }

  .anty-img-wrap > img {
    max-height: 100%;
  }

  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }
</style>
